package com.chj.leetcode.tijie900to950;

public class Code917_ReverseOnlyLetters {

	public static void reverseString(char[] s) {
		int l = 0;
		int r = s.length - 1;
		reverse(s, l, r);
	}

	public static void reverse(char[] chs, int l, int r) {
		while (l < r) {
			char tmp = chs[l];
			chs[l++] = chs[r];
			chs[r--] = tmp;
		}
	}

	public static boolean isAbc(char s) {
		if (s >= 'a' && s <= 'z') {
			return true;
		} else if (s >= 'A' && s <= 'Z') {
			return true;
		}
		return false;
	}

	public static String reverseOnlyLetters(String str) {
		char[] cs = str.toCharArray();
		char[] rcs = str.toCharArray();
		int n = cs.length;

		reverseString(rcs);

		int j = 0;
		for (int i = 0; i < n; i++) {
			if (isAbc(cs[i])) {
				while (!isAbc(rcs[j])) {
					j++;
				}
				cs[i] = rcs[j++];
			}
		}

		return String.valueOf(cs);
	}

	public static void main(String[] args) {
		String str = "ab-cd";
		System.out.println(reverseOnlyLetters(str));
	}
}
